package com.sbs.gaoxinqutoilet.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.adapter.ToiletAcceptRvAdapter;
import com.sbs.gaoxinqutoilet.base.BaseBackFragment;
import com.sbs.gaoxinqutoilet.entity.AcceptItemEntity;
import com.sbs.gaoxinqutoilet.entity.CountyEntity;
import com.sbs.gaoxinqutoilet.entity.HomeMenuEntity;
import com.sbs.gaoxinqutoilet.entity.MessageEvent;
import com.sbs.gaoxinqutoilet.entity.UserEntity;
import com.sbs.gaoxinqutoilet.eventbus.StartNewFragmentEvent;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constant;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.interfaces.ContyPopuListener;
import com.sbs.gaoxinqutoilet.interfaces.PopuClickListener;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.NetworkUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.view.MyDFButton;
import com.zhy.autolayout.AutoFrameLayout;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * Created by 聪明一只哈 on 2018/5/31.
 * Time: 2018/5/31  16:13
 */

public class ToiletBuildAcceptFragment extends BaseBackFragment {


    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_iv_menu)
    ImageView toolbarIvMenu;
    @BindView(R.id.toolbar_tv_menu)
    TextView toolbarTvMenu;
    @BindView(R.id.toolbar_rl_menu)
    AutoRelativeLayout toolbarRlMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.bt_buildaccept_filter)
    MyDFButton btBuildacceptFilter;
    @BindView(R.id.buildaccept_rv)
    RecyclerView buildacceptRv;
    @BindView(R.id.buildaccept_trefresh)
    TwinklingRefreshLayout buildacceptTrefresh;
    @BindView(R.id.buildaccept_fl)
    AutoFrameLayout buildacceptFl;


    @BindView(R.id.et_accept_hum)
    EditText etAcceptHum;
    @BindView(R.id.bt_accept_huming)
    Button btAcceptHuming;


    @BindView(R.id.accept_et_doornumber)
    EditText acceptEtDoornumber;
    @BindView(R.id.accept_et_doorname)
    EditText acceptEtDoorname;
    @BindView(R.id.accept_et_Iidnumber)
    EditText acceptEtIidnumber;
    @BindView(R.id.accept_tv_typeone)
    TextView acceptTvTypeone;
    @BindView(R.id.accept_tv_typetwo)
    TextView acceptTvTypetwo;
    @BindView(R.id.accept_tv_typethree)
    TextView acceptTvTypethree;
    @BindView(R.id.accept_tv_typefour)
    TextView acceptTvTypefour;
    @BindView(R.id.accept_tv_typefive)
    TextView acceptTvTypefive;
    @BindView(R.id.accept_tv_typesix)
    TextView acceptTvTypesix;
    @BindView(R.id.accept_tv_typeseven)
    TextView acceptTvTypeseven;
    @BindView(R.id.accept_tv_typeeight)
    TextView acceptTvTypeeight;
    @BindView(R.id.accept_tv_pass)
    TextView acceptTvPass;
    @BindView(R.id.accept_tv_fail)
    TextView acceptTvFail;
    @BindView(R.id.accept_tv_result)
    TextView acceptTvresult;
    @BindView(R.id.accept_address_conty)
    TextView acceptAddressConty;
    @BindView(R.id.accept_address_town)
    TextView acceptAddressTown;
    @BindView(R.id.tv_accept_huce_count)
    TextView tvAcceptHuceCcount;
    @BindView(R.id.accept_address_village)
    TextView acceptAddressVillage;
    @BindView(R.id.accept_reset)
    Button acceptReset;
    @BindView(R.id.all_sliding_licate_accept)
    AutoLinearLayout asla_aulla;
    @BindView(R.id.accept_done)
    Button acceptDone;
//    @BindView(R.id.bt_check_to_top)
//    Button acceptCheckTop;
    @BindView(R.id.builiaccept_drawlayout)
DrawerLayout builiacceptDrawlayout;
    Unbinder unbinder;

    //传过来的改造档案数据  存储在Bundle中
    private static final String ACCEPT_FILE = "accept_file";

    //侧滑菜单的view,所添加进的集合
    private List<View> viewacceptlist;

    //解析数据的条目集合
    private ArrayList<AcceptItemEntity.DataBean> buyItemList;
    private ToiletAcceptRvAdapter applyRvAdapter;

    //改造类型
    private List<String> typelist;
    //验收结果
    private List<String> accept_result_list = new ArrayList<>();


    private View emptyView;
    private View errorView;
    private View footView;
    private AcceptRequest acceptRequest;
    private Map<String, String> conditionmap = new HashMap<>();
    private HomeMenuEntity homemenu_buildfile;
    private BuildFileRequestCondition acceptConditionRequest;
    private ContyRequest cavRequest;
    private TwonRequest twonRequest;
    private VillageRequest villageRequest;

    //获取县乡村的name
    private List<String> namelist = new ArrayList<>();
    private ListPopupWindow acceptcontyPW;
    private ListPopupWindow accepttwonPW;
    private ListPopupWindow acceptvillagePW;
    private Button acceptCheckTop;
    private String token_data;

    public static ToiletBuildAcceptFragment newInstance(HomeMenuEntity homeMenuEntity) {
        Bundle args = new Bundle();
        args.putSerializable(ACCEPT_FILE, homeMenuEntity);
        ToiletBuildAcceptFragment fragment = new ToiletBuildAcceptFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_buildaccept, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(inflater,view);
        initListener();
        return attachToSwipeBack(view);
    }

    /**
     * 初始化view
     *
     * @param inflater
     */
    private void initView(LayoutInflater inflater,View view) {
        EventBus.getDefault().register(this);
        toolbarTitle.setText("户厕改造验收");

        token_data = SPUtil.getString(Constants.KEY_TOKEN, "");

        acceptCheckTop = (Button) view.findViewById(R.id.bt_check_to_top);


        toolbarTitle.setVisibility(View.VISIBLE);
        //设置回键
        initToolbarBack(toolbar);
        //返回按钮
        toolbarBack.setVisibility(View.VISIBLE);

        toolbarIvMenu.setVisibility(View.VISIBLE);
        //toolbarIvMenu.setImageResource(R.drawable.ic_add_apply);
        toolbarIvMenu.setImageResource(R.drawable.shaixuan);

//--------------------------------------------

        //获取传递过来的值
        Bundle arguments = getArguments();
        if (arguments != null) {
            homemenu_buildfile = (HomeMenuEntity) arguments.getSerializable(ACCEPT_FILE);
        }

//--------------------------------------------

//---------------验收结果-----------------------------

        accept_result_list.add("未验收");
        accept_result_list.add("合格");
        accept_result_list.add("不合格");

//---------------验收结果-----------------------------

        //添加刷新头和尾
        SinaRefreshView sinaHeader = new SinaRefreshView(_mActivity);
        sinaHeader.setArrowResource(R.drawable.arrow);
        sinaHeader.setTextColor(0xff745D5C);
        buildacceptTrefresh.setHeaderView(sinaHeader);

        LoadingView loadingView = new LoadingView(_mActivity);
        buildacceptTrefresh.setBottomView(loadingView);
        buildacceptTrefresh.setEnableLoadmore(false);

        //初始化index
        index = 0;
        buyItemList = new ArrayList<>();
        applyRvAdapter = new ToiletAcceptRvAdapter(R.layout.item_toilet_accept, buyItemList);
        buildacceptRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        buildacceptRv.setAdapter(applyRvAdapter);
        applyRvAdapter.disableLoadMoreIfNotFullPage(buildacceptRv);

        emptyView = inflater.inflate(R.layout.view_empty, buildacceptRv, false);
        errorView = inflater.inflate(R.layout.view_error, buildacceptRv, false);
        footView = inflater.inflate(R.layout.view_foot, buildacceptRv, false);

    }


    /**
     * 监听
     */
    private void initListener() {

        toolbarIvMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(builiacceptDrawlayout.isDrawerOpen(GravityCompat.END)){
                    builiacceptDrawlayout.closeDrawer(GravityCompat.END);
                }else{
                    builiacceptDrawlayout.openDrawer(GravityCompat.END);
                }
                if (viewacceptlist == null) {
                    viewacceptlist = new ArrayList<>();
                }

                //清空参数集合
                if (conditionmap != null) {
                    conditionmap.clear();
                }


                //改造类型value
                if (typelist == null) {
                    typelist = new ArrayList<>();
                }

            }
        });

        //---------applyRvAdapter条目点击---------------------------
        //applyRvAdapter条目点击事件-->点击整个条目,adapter中,子view不用addonclicklinstener
        applyRvAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ArrayList<AcceptItemEntity.DataBean> list = (ArrayList<AcceptItemEntity.DataBean>) adapter.getData();
                AcceptItemEntity.DataBean rowsBean = list.get(position);
                if (rowsBean != null) {


                    UserEntity userEntity = SPUtil.getBeanValue(Constants.KEY_USER, UserEntity.class);
                    LogUtils.i("hashiqiLevel", "onItemClick: "+userEntity.getOpt_level());
                    if (userEntity != null) {
                        //验收,只有乡级可以编辑
                        //301 市  302 县  303 乡 304*
                        if ("303".equals(userEntity.getOpt_level())) {
                            rowsBean.setEdit(true);
                            rowsBean.setLevel(userEntity.getOpt_level());
                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletAcceptDetialFragment.newInstance(list.get(position))));
                        }else{
                            rowsBean.setEdit(false);
                            rowsBean.setLevel(userEntity.getOpt_level());
                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletAcceptDetialFragment.newInstance(list.get(position))));

                        }
                        // 只有未验收才能进行编辑,合格和不合格就只能进行预览查看
//                        switch (rowsBean.getYanshou_result_n()) {
//                            case "合格":
//                            case "不合格":
//                                //除去村级别
//                                if (!"304".equals(userEntity.getOpt_level())) {
//                                    rowsBean.setEdit(false);
//                                    EventBus.getDefault().post(new StartNewFragmentEvent(ToiletAcceptDetialFragment.newInstance(list.get(position))));
//
//                                }
//                                break;
//                            case "未验收":
//                                //只有乡的级别才能进行编辑
//                                if ("303".equals(userEntity.getOpt_level())) {
//                                    rowsBean.setEdit(true);
//                                    EventBus.getDefault().post(new StartNewFragmentEvent(ToiletAcceptDetialFragment.newInstance(list.get(position))));
//                                } else if ("301".equals(userEntity.getOpt_level())
//                                        || "302".equals(userEntity.getOpt_level())) {
//
//                                    //除去村级别,其他两个级别只能进行查看
//                                    rowsBean.setEdit(false);
//                                    EventBus.getDefault().post(new StartNewFragmentEvent(ToiletAcceptDetialFragment.newInstance(list.get(position))));
//
//
//                                }
//                                break;
//
//                            default:
//
//                                break;
//                        }
                    }


                }

            }
        });


        //---------列表的刷新---------------------------------------
        // buildacceptTrefresh
        buildacceptTrefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                Log.e("显示", "refresh");

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("显示", "refreshRun");
                        //清空参数集合
                        if (conditionmap != null) {
                            conditionmap.clear();
                        }
//                        mBuyAdapter.removeAllFooterView();
                        requestRefresh();
                    }
                }, 2000);
            }

            @Override
            public void onFinishRefresh() {
                super.onFinishRefresh();
                Log.e("显示", "Finishrefresh");
                applyRvAdapter.setEnableLoadMore(true);

            }
        });


        //预加载
        applyRvAdapter.setPreLoadNumber(Constant.PRE_SIZE);
        //设置动画
        applyRvAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);


        //---------applyRvAdapter加载数据---------------------------
        //applyRvAdapter加载数据的监听
        applyRvAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                int currentSize = applyRvAdapter.getData().size();
                if (!TextUtils.isEmpty(mTotalSize)) {

                    int totalSize = Integer.parseInt(mTotalSize);
                    if (currentSize >= totalSize) {
                        applyRvAdapter.loadMoreEnd();
                    } else {
                        index++;

                        if (conditionmap != null && conditionmap.size() > 0) {
                            LogUtils.i("验收检查刷新", "有条件的: ");
                            conditionLoadMore(conditionmap, index * pageSize, pageSize);
                        } else {
                            // loadMoreData(index, pageSize);
                            LogUtils.i("验收检查刷新", "无条件的: ");
                            loadMoreData(index * pageSize, pageSize);
                        }
                    }
                }

            }
        }, buildacceptRv);

        //响应键盘回车
        etAcceptHum.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    hideSoftInput();
                    String huname = etAcceptHum.getText().toString().trim();
                    if (!TextUtils.isEmpty(huname)) {
                        conditionmap.put("b.huming@m", huname);
                    }

                    index = 0;
                    conditionLoadMore(conditionmap, index, pageSize);

                    etAcceptHum.setText("");

                }

                return true;
            }
        });


    }


    private boolean isSelectedAcceptOne, isSelectedAcceptTwo, isSelectedAcceptThree, isSelectedAcceptFour, isSelectedAcceptFive,
            isSelectedAcceptSix, isSelectedAcceptSeven, isSelectedAcceptEight, isSelectedAcceptPass, isSelectedAcceptFail;

    @OnClick({R.id.bt_buildaccept_filter,R.id.bt_accept_huming,
            R.id.accept_tv_typeone, R.id.accept_tv_typetwo, R.id.accept_tv_typethree,
            R.id.accept_tv_typefour, R.id.accept_tv_typefive, R.id.accept_tv_typesix,
            R.id.accept_tv_typeseven, R.id.accept_tv_typeeight, R.id.accept_tv_pass,
            R.id.accept_tv_fail, R.id.accept_reset, R.id.accept_done, R.id.accept_tv_result,
            R.id.accept_address_conty, R.id.accept_address_town, R.id.accept_address_village,
            R.id.bt_check_to_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //顶部户名查询
            case R.id.bt_accept_huming:

                String huname = etAcceptHum.getText().toString();
                if (!TextUtils.isEmpty(huname)) {
                    conditionmap.put("b.huming@m", huname);
                }

                index = 0;
                conditionLoadMore(conditionmap, index, pageSize);

                etAcceptHum.setText("");

                break;
            //返回顶部
            case R.id.bt_check_to_top:

                buildacceptRv.smoothScrollToPosition(0);

                break;

            //筛选按钮
            case R.id.bt_buildaccept_filter:
               // builiacceptDrawlayout.openDrawer(Gravity.END);

//                if(builiacceptDrawlayout.isDrawerOpen(Gravity.END)){
//                    builiacceptDrawlayout.closeDrawer(Gravity.END);
//                }else{
//                    builiacceptDrawlayout.openDrawer(Gravity.END);
//                }
//                if (viewacceptlist == null) {
//                    viewacceptlist = new ArrayList<>();
//                }
//
//                /*
//                 * 设置map集合对应的字段
//                 * 1.所属地:(a.area_id@m,"") 户名:(a.huming@m,"")  身份证号:(a.cert_no@m,"")
//                 * 初始化时将前三个参数添加进集合
//                 * 改造类型: a.gaizao_type@i      , 拼接多选条件
//                 * 简易 :jy(,208)
//                 * 双坑:sk (,206)
//                 * 双翁:sw (,205)
//                 * 分集:fj (,207)
//                 * 小三格:xsg (,202)
//                 * 水冲式:scs (,203)
//                 * 沼气池:zqc(,204)
//                 * 单户单坑+大三格:ddjd(,201)
//                 * 3.验收结果:  yanshou_result 合格 :1  不合格:0
//                 * */
//
//
//                //清空参数集合
//                if (conditionmap != null) {
//                    conditionmap.clear();
//                }
//
//
//                //改造类型value
//                if (typelist == null) {
//                    typelist = new ArrayList<>();
//                }

                break;

            //县乡村三级列表
            case R.id.accept_address_conty:
                acceptcontyPW = new ListPopupWindow(_mActivity);
                setPopuDataList(view, acceptcontyPW, contylist);
                setPopuClickListenerList(new ContyPopuListener() {
                    @Override
                    public void show(CountyEntity Centity, String text) {
                        acceptAddressConty.setText(Centity.getText());
                        //showLoadingDialog("正在加载乡镇数据");
                        SPUtil.putString(Constants.ACCEPT_CONTY_LEVEL, "xian");
                        SPUtil.putString(Constants.ACCEPT_CONTY_ID, Centity.getValue());

                        getTownList(Centity.getValue());


                    }
                });

                break;

            case R.id.accept_address_town:

                String conty_address = acceptAddressConty.getText().toString().trim();
                if (TextUtils.isEmpty(conty_address) || "(区)县".equals(conty_address)) {
                    showShortToast("请先选择县级单位");
                    return;
                } else {

                    try {
                        if (twonlist != null && twonlist.size() > 0) {
                            accepttwonPW = new ListPopupWindow(_mActivity);
                            setPopuDataList(view, accepttwonPW, twonlist);
                            setPopuClickListenerList(new ContyPopuListener() {
                                @Override
                                public void show(CountyEntity Centity, String text) {

                                    acceptAddressTown.setText(Centity.getText());
                                    SPUtil.putString(Constants.ACCEPT_CONTY_LEVEL, "xiang");
                                    SPUtil.putString(Constants.ACCEPT_CONTY_ID, Centity.getValue());
                                   // showLoadingDialog("正在加载村级数据");
                                    getVillageList(Centity.getValue());

                                }
                            });
                        }
                    } catch (Exception e) {
                        LogUtils.i("list为null", "乡级列表onViewClicked: " + e.toString());
                    }

                }

                break;

            case R.id.accept_address_village:

                String town_address = acceptAddressTown.getText().toString().trim();
                if (TextUtils.isEmpty(town_address) || "乡".equals(town_address)) {
                    showShortToast("请先选择乡级单位");
                    return;
                } else {

                    try {
                        if (villagelist != null && villagelist.size() > 0) {
                            acceptvillagePW = new ListPopupWindow(_mActivity);
                            setPopuDataList(view, acceptvillagePW, villagelist);
                            setPopuClickListenerList(new ContyPopuListener() {
                                @Override
                                public void show(CountyEntity Centity, String text) {
                                    acceptAddressVillage.setText(Centity.getText());
                                    SPUtil.putString(Constants.ACCEPT_CONTY_LEVEL, "cun");
                                    SPUtil.putString(Constants.ACCEPT_CONTY_ID, Centity.getValue());

                                }
                            });
                        }
                    } catch (Exception e) {
                        LogUtils.i("list为null", "村级列表onViewClicked: " + e.toString());
                    }


                }


                break;


            //8个改造类型
            case R.id.accept_tv_typeone:
                if (!isSelectedAcceptOne) {
                    view.setSelected(true);
                    typelist.add("208");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("208")) {
                        typelist.remove("208");
                    }
                }
                isSelectedAcceptOne = !isSelectedAcceptOne;
                if (view.isSelected()) {
                    viewacceptlist.add(view);
                }
                break;
            case R.id.accept_tv_typetwo:
                if (!isSelectedAcceptTwo) {
                    view.setSelected(true);
                    typelist.add("206");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("206")) {
                        typelist.remove("206");
                    }
                }
                isSelectedAcceptTwo = !isSelectedAcceptTwo;
                if (view.isSelected()) {
                    viewacceptlist.add(view);
                }
                break;
            case R.id.accept_tv_typethree:
                if (!isSelectedAcceptThree) {
                    view.setSelected(true);
                    typelist.add("205");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("205")) {
                        typelist.remove("205");
                    }
                }
                isSelectedAcceptThree = !isSelectedAcceptThree;
                if (view.isSelected()) {
                    viewacceptlist.add(view);
                }
                break;
            case R.id.accept_tv_typefour:
                if (!isSelectedAcceptFour) {
                    view.setSelected(true);
                    typelist.add("207");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("207")) {
                        typelist.remove("207");
                    }
                }
                isSelectedAcceptFour = !isSelectedAcceptFour;
                if (view.isSelected()) {
                    viewacceptlist.add(view);
                }
                break;
            case R.id.accept_tv_typefive:
                if (!isSelectedAcceptFive) {
                    view.setSelected(true);
                    typelist.add("202");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("202")) {
                        typelist.remove("202");
                    }
                }
                isSelectedAcceptFive = !isSelectedAcceptFive;
                if (view.isSelected()) {
                    viewacceptlist.add(view);
                }
                break;
            case R.id.accept_tv_typesix:
                if (!isSelectedAcceptSix) {
                    view.setSelected(true);
                    typelist.add("203");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("203")) {
                        typelist.remove("203");
                    }
                }
                isSelectedAcceptSix = !isSelectedAcceptSix;
                if (view.isSelected()) {
                    viewacceptlist.add(view);
                }
                break;
            case R.id.accept_tv_typeseven:
                if (!isSelectedAcceptSeven) {
                    view.setSelected(true);
                    typelist.add("204");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("204")) {
                        typelist.remove("204");
                    }
                }
                isSelectedAcceptSeven = !isSelectedAcceptSeven;
                if (view.isSelected()) {
                    viewacceptlist.add(view);
                }
                break;
            case R.id.accept_tv_typeeight:
                if (!isSelectedAcceptEight) {
                    view.setSelected(true);
                    typelist.add("201");

                } else {
                    view.setSelected(false);
                    if (typelist.contains("201")) {
                        typelist.remove("201");
                    }
                }
                isSelectedAcceptEight = !isSelectedAcceptEight;
                if (view.isSelected()) {
                    viewacceptlist.add(view);
                }
                break;

            //验收结果
            case R.id.accept_tv_result:

                ListPopupWindow acceptResultPopupWindow = new ListPopupWindow(_mActivity);
                setPopuData(view, acceptResultPopupWindow, accept_result_list);
                setPopuClickListener(new PopuClickListener() {
                    @Override
                    public void show(String mess) {
                        acceptTvresult.setText(mess);
                    }
                });

                break;
            case R.id.accept_reset:
                for (View v : viewacceptlist) {
                    v.setSelected(false);
                }
                resetbooleanacceptstate();
                viewacceptlist.clear();

                //清空参数集合
                if (conditionmap != null) {
                    conditionmap.clear();
                }
                acceptTvresult.setText("选择验收结果");
                acceptAddressConty.setText("(区)县");
                acceptAddressTown.setText("乡");
                acceptAddressVillage.setText("村");
                acceptEtDoornumber.setText("");
                break;
            case R.id.accept_done:

                showLoadingDialog();

                //将参数添加到map集合中,添加时进行校验,3个都是选填
                String addressConty = acceptAddressConty.getText().toString();
                String addressTown = acceptAddressTown.getText().toString();
                String addressvillage = acceptAddressVillage.getText().toString();

                if (!"(区)县".equals(addressConty) | !"乡".equals(addressTown) | !"村".equals(addressvillage)) {
                    String conty_level = SPUtil.getString(Constants.ACCEPT_CONTY_LEVEL, "");
                    if ("xian".equals(conty_level)) {
                        if (conditionmap.containsKey("b.xiang_area_id")) {
                            conditionmap.remove("b.xiang_area_id");
                        }
                        if (conditionmap.containsKey("b.area_id")) {//a.area_id
                            conditionmap.remove("b.area_id");
                        }
                        conditionmap.put("b.xian_area_id", SPUtil.getString(Constants.ACCEPT_CONTY_ID, ""));
                    } else if ("xiang".equals(conty_level)) {
                        if (conditionmap.containsKey("b.xian_area_id")) {
                            conditionmap.remove("b.xian_area_id");
                        }
                        if (conditionmap.containsKey("b.area_id")) {
                            conditionmap.remove("b.area_id");
                        }
                        conditionmap.put("b.xiang_area_id", SPUtil.getString(Constants.ACCEPT_CONTY_ID, ""));
                    } else if ("cun".equals(conty_level)) {
                        if (conditionmap.containsKey("b.xian_area_id")) {
                            conditionmap.remove("b.xian_area_id");
                        }
                        if (conditionmap.containsKey("b.xiang_area_id")) {
                            conditionmap.remove("b.xiang_area_id");
                        }
                        conditionmap.put("b.area_id", SPUtil.getString(Constants.ACCEPT_CONTY_ID, ""));
                    }
                }


//                String huname = acceptEtDoorname.getText().toString();
//                if (!TextUtils.isEmpty(huname)) {
//                    conditionmap.put("a.huming@m", huname);
//                }
                String hunnumber = acceptEtDoornumber.getText().toString();
                if (!TextUtils.isEmpty(hunnumber)) {
                    conditionmap.put("b.hubianhao@m", hunnumber);
                }

                String acceptResult = acceptTvresult.getText().toString().trim();
                if (!TextUtils.isEmpty(acceptResult)) {

                    switch (acceptResult) {
                        case "合格":
                            conditionmap.put("a.yanshou_result", "1");
                            break;
                        case "不合格":
                            conditionmap.put("a.yanshou_result", "0");
                            break;
                        case "未验收":
                            conditionmap.put("a.yanshou_result", "-1");
                            break;

                        default:

                            break;
                    }

                }

                //关闭侧滑放在return语句之后
                builiacceptDrawlayout.closeDrawer(GravityCompat.END);

//=========================确定后view状态重置=======================================
                for (View v : viewacceptlist) {
                    v.setSelected(false);
                }
                resetbooleanacceptstate();
                viewacceptlist.clear();
//=========================改造类型====================================================

                buildtypeValue();

//=========================根据map集合里的参数请求筛选数据=================================

                index = 0;
                conditionLoadMore(conditionmap, index, pageSize);

                syso(conditionmap);

                //置为空
                acceptEtDoorname.setText("");
                acceptEtDoornumber.setText("");
                acceptEtIidnumber.setText("");
                acceptTvresult.setText("选择验收结果");
                acceptAddressConty.setText("(区)县");
                acceptAddressTown.setText("乡");
                acceptAddressVillage.setText("村");

                cancelLoadingDialog();
                break;
        }
    }

    /**
     * 改造类型 单选或者双选
     */
    private void buildtypeValue() {
        //conditionmap
        StringBuilder statue_value = new StringBuilder();
        if (typelist != null && typelist.size() > 0) {

            if (typelist.size() > 1) {
                //多个,多选,需要用","拼接value
                for (int i = 0; i < typelist.size(); i++) {
                    statue_value.append(typelist.get(i) + ",");
                }
            } else {
                //只有一个,单选,不用拼接value
                statue_value.append(typelist.get(0));
            }

            String sv_temp = statue_value.toString().trim();
            if (sv_temp.endsWith(",")) {
                LogUtils.i("statuevalue", "if: " + sv_temp);
                sv_temp = sv_temp.substring(0, statue_value.length() - 1);
                LogUtils.i("statuevalue", "if: " + sv_temp);
            }

            conditionmap.put("a.gaizao_type@i", sv_temp);
        }
        typelist.clear();
    }


    //模拟输出测验
    private void syso(Map<String, String> conditionmap) {
        Set<Map.Entry<String, String>> entrySet = conditionmap.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> me = iterator.next();
            String key = me.getKey();
            String value = me.getValue();
            LogUtils.i("验收conditionmap", key + ":" + value);

        }

    }


    /**
     * 重置状态
     */
    private void resetbooleanacceptstate() {
        isSelectedAcceptOne = false;
        isSelectedAcceptTwo = false;
        isSelectedAcceptThree = false;
        isSelectedAcceptFour = false;
        isSelectedAcceptFive = false;
        isSelectedAcceptSix = false;
        isSelectedAcceptSeven = false;
        isSelectedAcceptEight = false;
        isSelectedAcceptPass = false;
        isSelectedAcceptFail = false;

    }


    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalist
     */
    private void setPopuData(View view, final ListPopupWindow mPopupWindow, final List<String> datalist) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, datalist);
        mPopupWindow.setAdapter(adapter);

        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(view);
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (popuClickListener != null) {
                    popuClickListener.show("" + datalist.get(position));
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();
    }

//====================listpopuwindow  县 村=======================================

    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalists
     */

    private void setPopuDataList(View view, final ListPopupWindow mPopupWindow, final List<CountyEntity> datalists) {

        //清空集合,添加数据
        namelist.clear();
        for (CountyEntity ce : datalists) {
            namelist.add(ce.getText());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, namelist);
        mPopupWindow.setAdapter(adapter);

        //弹出的位置  弹出锚点
        //mPopupWindow.setAnchorView(view);
        mPopupWindow.setAnchorView(asla_aulla);

        //mPopupWindow.setVerticalOffset(ConvertUtils.dp2px(_mActivity, 12));

//        mPopupWindow
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//        mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);


        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (popuClickListenerList != null) {
                    popuClickListenerList.show(datalists.get(position), datalists.get(position).getText());
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();


    }

    public ContyPopuListener popuClickListenerList;

    public void setPopuClickListenerList(ContyPopuListener popuClickListenerList) {
        this.popuClickListenerList = popuClickListenerList;
    }
//--------------------------------------------------------------------------------------


    /**
     * eventbus 页面跳转验证页面,事件接受
     *
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {

        LogUtils.i("返回跳转", messageEvent.getMessage());
        if ("360".equals(messageEvent.getMessage())) {
            //提交成功
            LogUtils.i("返回跳转", messageEvent.getMessage());
            new Handler() {
            }.postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestRefresh();
                }
            }, 500);
        }
    }


    //Rv一次性加载多少个条目,设为5条
    private int pageSize = 5;
    //页数
    private int index;

    /**
     * 页面条转过来就刷新数据
     */
    private void requestRefresh() {
        Log.e("显示", "指示refresh " + index);
        applyRvAdapter.setEnableLoadMore(false);
        buyItemList.clear();
        applyRvAdapter.setNewData(buyItemList);

        if (buildacceptTrefresh != null) {
            buildacceptTrefresh.finishRefreshing();
        }
        index = 0;
        loadMoreData(index, pageSize);
    }

    /**
     * 页面加载动画结束就调用  loadMoreData(index, pageSize);
     * 所以  将两个方法紧挨着
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        //添加家在逻辑
        Log.e("显示", "指示enter " + index);

        loadMoreData(index, pageSize);


        //获取县乡村数据
        getLevelData();

    }

    /**
     * 获取县乡村数据
     */
    private void getLevelData() {
        //获取县,乡,村级列表数据
        //获取个人信息
        UserEntity userEntity = SPUtil.getBeanValue(Constants.KEY_USER, UserEntity.class);
        if (userEntity != null) {
            //获取县级列表
            getContyList(userEntity);
        }
    }


    //县级列表
    private List<CountyEntity> contylist = null;
    //乡级列表
    private List<CountyEntity> twonlist = null;
    //村级列表
    private List<CountyEntity> villagelist = null;

    private void getContyList(UserEntity userEntity) {
        //需要拼接
        // String addnew_url = HttpApis.addnew_info+userEntity.getArea_id()+"/"+userEntity.getArea_level();
        String addnew_url = HttpApis.addnew_info + userEntity.getArea_id() + "/" + "3";


        //showLoadingDialog("正在加载县级数据");
        if (cavRequest == null) {
            cavRequest = new ContyRequest();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        LogUtils.i("乡级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url,map, cavRequest);
    }

    private void getTownList(String conty_id) {
        String addnew_url = HttpApis.addnew_info + conty_id + "/" + "4";


        if (twonRequest == null) {
            twonRequest = new TwonRequest();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);

        LogUtils.i("县级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url,map, twonRequest);

    }

    private void getVillageList(String teon_id) {
        String addnew_url = HttpApis.addnew_info + teon_id + "/" + "5";

        if (villageRequest == null) {
            villageRequest = new VillageRequest();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        LogUtils.i("村级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url,map, villageRequest);
    }

    private class ContyRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            LogUtils.i("乡级列表", "success: " + jsonStr);

            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();

            contylist = JsonUtil.json2Collection(jsonStr, type);

          //  cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("乡级列表", "error: " + error);

           // cancelLoadingDialog();
        }
    }

    private class TwonRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            LogUtils.i("县级列表", "success: " + jsonStr);

            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();

            twonlist = JsonUtil.json2Collection(jsonStr, type);

           // cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("县级列表", "error: " + error);

            //cancelLoadingDialog();
        }
    }

    private class VillageRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            LogUtils.i("村级列表", "success: " + jsonStr);

            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();

            villagelist = JsonUtil.json2Collection(jsonStr, type);

           // cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("村级列表", "error: " + error);

           // cancelLoadingDialog();
        }
    }


    /**
     * 加载数据
     *
     * @param index    页数
     * @param pageSize
     */
    private void loadMoreData(int index, int pageSize) {

        if (index == 0) {
            showLoadingDialog();
        }
        Log.e("显示", "指示loadmore " + index);

        acceptCheckTop.setText("顶部");

        //page=0&rows=5
        String mAcception_item_url = HttpApis.acception_item;
        Log.e("mAcception_item", mAcception_item_url);

        if (acceptRequest == null) {
            acceptRequest = new AcceptRequest();
        }

        HashMap<String, String> params = new HashMap<>();
        params.put("iud", homemenu_buildfile.getIud());
        params.put("start", String.valueOf(index));
        params.put("pagesize", String.valueOf(pageSize));
        params.put("token",token_data);

        HttpUtils.requestGet(_mActivity, mAcception_item_url, params, acceptRequest);

    }


    /**
     * 条件筛选
     *
     * @param index
     * @param pageSize
     */
    private void conditionLoadMore(Map<String, String> conditionmap, int index, int pageSize) {

        if (index == 0) {
            showLoadingDialog();
        }
        Log.e("显示", "指示loadmore " + index);

        //page=0&rows=5
        String mAcception_item_url = HttpApis.acception_item;
        LogUtils.i("buildfile_condition", mAcception_item_url);

        if (acceptConditionRequest == null) {
            acceptConditionRequest = new BuildFileRequestCondition();
        }

        HashMap<String, String> params = new HashMap<>();
        params.put("iud", homemenu_buildfile.getIud());
        params.put("start", String.valueOf(index));
        params.put("pagesize", String.valueOf(pageSize));
        params.put("token",token_data);

        LogUtils.i("验收检查刷新", "conditionLoadMore: " + conditionmap.size());
        if (conditionmap != null && conditionmap.size() > 0) {
            params.putAll(conditionmap);
        }

        HttpUtils.requestGet(_mActivity, mAcception_item_url, params, acceptConditionRequest);

    }


    //请求列表数据
    private class AcceptRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            LogUtils.i("验收列表", jsonStr);

            AcceptItemEntity acceptItemEntity = GsonTools.changeGsonToBean(jsonStr, AcceptItemEntity.class);
            //将数据解析出来
            processData(acceptItemEntity);
            applyRvAdapter.loadMoreComplete(); //加载完

            if (index == 0) {
                cancelLoadingDialog();
            }

        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("验收列表", error);
            if (index == 0 || !NetworkUtils.isConnected(_mActivity)) {
                applyRvAdapter.setEmptyView(errorView);
            } else {
                applyRvAdapter.setEmptyView(emptyView);
                applyRvAdapter.loadMoreFail();
            }

            if (index == 0) {
                cancelLoadingDialog();
            }
        }
    }

    //临时存放此处
    private String mTotalSize;

    /**
     * 讲解析出来的数据,进行加载
     *
     * @param acceptItemEntity
     */
    private void processData(AcceptItemEntity acceptItemEntity) {
        LogUtils.i("显示", "指示process " + index);

        if (acceptItemEntity != null) {
            mTotalSize = acceptItemEntity.getRecordsTotal();
            tvAcceptHuceCcount.setText(mTotalSize+"户");
            LogUtils.i("加载验收数据", "指示process " + mTotalSize);
            if (Integer.parseInt(mTotalSize) > 0) {
                if (index == 0) {
                    //设置新数据
                    LogUtils.i("加载验收数据", "index==0 ");

                    applyRvAdapter.setNewData(acceptItemEntity.getData());
                } else {
                    LogUtils.i("加载验收数据", "index=" + index);
                    applyRvAdapter.addData(acceptItemEntity.getData());
                }
            } else {
                applyRvAdapter.setNewData(null);
                applyRvAdapter.setEmptyView(emptyView);
            }
            LogUtils.i("显示", "数据u" + applyRvAdapter.getData().size());
        } else {
            LogUtils.i("加载验收数据", "指示process acceptItemEntity为null");
            applyRvAdapter.setEmptyView(emptyView);
        }

    }


    //=========================根据条件请求列表数据==========================================================
    //根据条件请求列表数据
    private class BuildFileRequestCondition extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            LogUtils.i("buildfile_condition", "success" + jsonStr);
            AcceptItemEntity acceptItemEntity = GsonTools.changeGsonToBean(jsonStr, AcceptItemEntity.class);
            //将数据解析出来
            processSetDataCondition(acceptItemEntity);
            //processData(acceptItemEntity);
            //加载完
            applyRvAdapter.loadMoreComplete();

            if (index == 0) {
                cancelLoadingDialog();
            }

        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("buildfile_condition", "error: " + error);
            if (!NetworkUtils.isConnected(_mActivity)) {
                applyRvAdapter.setEmptyView(errorView);
            } else {
                applyRvAdapter.setEmptyView(errorView);
                applyRvAdapter.loadMoreFail();
            }


            cancelLoadingDialog();
        }
    }

    //根据条件解析数据
    private void processSetDataCondition(AcceptItemEntity acceptItemEntity) {

        if (acceptItemEntity != null) {
            mTotalSize = acceptItemEntity.getRecordsTotal();

            acceptCheckTop.setText(mTotalSize);
            tvAcceptHuceCcount.setText(mTotalSize+"户");

            //清空原有集合数据
            if (Integer.parseInt(mTotalSize) > 0) {
                if (index == 0) {
                    //设置新数据
                    applyRvAdapter.setNewData(acceptItemEntity.getData());
                } else {
                    applyRvAdapter.addData(acceptItemEntity.getData());
                }
            } else {
                // TODO: 2018/6/16 这里出现一个问题:使用setEmptyView()之前的将之前的数据setNewData(null)
                applyRvAdapter.setNewData(null);
                applyRvAdapter.setEmptyView(emptyView);
            }
            LogUtils.e("显示", "数据u" + applyRvAdapter.getData().size());
        } else {
            applyRvAdapter.setEmptyView(emptyView);
        }

    }

//=========================根据条件请求列表数据================================================================


    //-------------设置popu传值接口-----------------------------------------------------------
    public PopuClickListener popuClickListener;

    public void setPopuClickListener(PopuClickListener popuClickListener) {
        this.popuClickListener = popuClickListener;
    }
//--------------------------------------------------------------------------------------

    @Override
    public boolean onBackPressedSupport() {

        if (builiacceptDrawlayout.isDrawerOpen(GravityCompat.END)) {
            builiacceptDrawlayout.closeDrawer(GravityCompat.END);
            return true;
        } else {
            return false;
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtils.i("hashqi", "onPause: ");
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();
    }
}
